/*
 ------------------------------------------------------------------------------
 Copyright (C) 2006-2007 Team Blur.

 This file is part of the Quantum Engine source code.

 The Quantum Engine source code is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or (at your
 option) any later version.

 The Quantum Engine source code is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 more details.

 You should have received a copy of the GNU General Public License along with
 the Quantum Engine source code; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ------------------------------------------------------------------------------
*/


#include "client.h"

/*
 ==================
 CL_SendCommands
 ==================
*/
void CL_SendCommands (void){
	if (cls.state < CS_CONNECTED)
		return;

	CL_BuildUserCmd();

	byte		buffer[MAX_MSGLEN];
	ByteBuffer		msg;
	userCmd_t	*usrcmd=&cl.userCmds[0];
	int			index;
	int			i;

	if (cls.state < CS_CONNECTED)
		return;

	// Initialize the message buffer
	msg.Init(buffer, sizeof(buffer), false);

	// Write the server id so the server can tell if this is from the current
	// server state
	msg.WriteLong(cl.serverId);

	// Write the last message sequence we received, which can be used for delta
	// compression
	msg.WriteLong(0);

	// Write the last reliable command we received
	msg.WriteLong(0);

	// We want to send all the user commands that were generated in the last
	// few packets, so even if a couple packets are dropped in a row, all the
	// user commands will make it to the server
	if (cl_packetDup->integerValue < 0)
		CVar_SetInteger(cl_packetDup, 0);
	else if (cl_packetDup->integerValue > 5)
		CVar_SetInteger(cl_packetDup, 5);

	if (cls.state >= CS_PRIMED){
		// Begin a client move
		msg.WriteByte(CLC_MOVE);
		//write user command number
		msg.WriteByte(1);

		// Write all the user commands
		msg.WriteLong(usrcmd->time);
		msg.WriteByte(usrcmd->flags);
		msg.WriteLong(usrcmd->buttons);
		msg.WriteChar(usrcmd->forwardMove);
		msg.WriteChar(usrcmd->rightMove);
		msg.WriteChar(usrcmd->upMove);
		msg.WriteShort(usrcmd->angles[0]);
		msg.WriteShort(usrcmd->angles[1]);
		msg.WriteShort(usrcmd->angles[2]);
	}

	// Write the EOF
	msg.WriteByte(CLC_EOF);

	ENetPacket * packet = enet_packet_create (msg.data,msg.getBytesWritten(),0);
    enet_peer_send (cls.server, 0, packet);
    enet_host_flush (cls.client);
}
